var maxDrugRow = 13;
var maxInjectRow = 11;

var MY_WEST_PRESCRIPTION = (function() {

	/**
	 * 设置打印内容
	 *
	 * @param prescription 该处方的所有信息
	 * */
	function resetPrintBody(outpatient) {

		// 打印头部
		userInfo(outpatient);

		// 设置统一内容医生，日期等 add by zhengxb
		$('div.pill-list-content').find('ul').empty();
		var orders = [];
		var injectOrders = [];

		var doctorName = outpatient.medical.doctorName;
		var issueDt = outpatient.westPrescription.prescriptions[0].issueDt;//处方出具日期
		var issueDtTxt = (issueDt == null?'':new Date(issueDt).format('yyyy-MM-dd'));

		orders = outpatient.westPrescription.prescriptions;

		$('div.pill-detailInfo').find('span.add-date').text(issueDtTxt);
		$('div.pill-bottom-info').find('span[name="doctorName"]').text(doctorName);
		$('div.pill-inject-table').find('span[name="doctorName"]').text(doctorName);
		// 诊断
		$('div.pill-detailInfo').find('span.diagnosis').text( outpatient.medical.diagnosis == null?'':outpatient.medical.diagnosis);
		var totalMoney = calAmout(orders);
		$('span.total-money').text(totalMoney);
		//----------------------------add by zhengxb-----------------------------------------------------------------------------

		$('div.copy-print').remove();
		printDrugOrder($('div.drug-order'), orders, maxDrugRow, 1);
		//更新页码
		var $printDrug = $('div.drug-order');
		$printDrug.find('span.all-page').text($printDrug.length);
		$printDrug.each(function(idx, drug){
			$printDrug.eq(idx).find('span.this-page').text(idx+1);
			if (idx+1 < $printDrug.length) {
				$printDrug.eq(idx).find('p.pill-list-hint i').text('（以下空白，详见下页）');
			}
		})

		var lastIdx = printDrugOrder($('div.drug-order-plus'), orders, maxDrugRow, 1);

		//更新页码
		var $printDrugPlus = $('div.drug-order-plus');
		$printDrugPlus.find('span.all-page').text($printDrug.length);
		$printDrugPlus.each(function(idx, drug){
			$printDrugPlus.eq(idx).find('span.this-page').text(idx+1);
			if (idx+1 < $printDrug.length) {
				$printDrugPlus.eq(idx).find('p.pill-list-hint i').text('（以下空白，详见下页）');
			}
		})
		//更新含附加费处方的总金额
//		var totalMoney = $('#totalMoney').text();
//		$printDrugPlus.find('span[name="totalPrice"]').text(totalMoney);
		var $setUl = $printDrugPlus.last().find('div.pill-list-content ul');
		lastIdx++;
		var plusRow = '';
		plusRow += '<li class="pill-list-item li-w5">';
		plusRow += '<span>'+lastIdx+'、</span>';
		plusRow += '</li>';
		plusRow += '<li class="pill-list-item li-w90">';
		plusRow += '<span>附加费</span>';
		plusRow += '</li>';
		$setUl.append(plusRow);

		/*
		//附加费
		var totalPricePlus = $('#westPrescriptionExtraAmout').val();
		printPlusOrder(plusOrders, toMoney(totalPricePlus));
		*/

		/*
		if (injectOrders.length > 0) {
			console.log('有注射单');
//			$('#printDiv .inject-order').show();
			printInjectOrder($('div.inject-order'), injectOrders, 1, maxInjectRow);
			var $printInject = $('div.inject-order');
			$printInject.find('span.all-page').text($printInject.length);
			$printInject.each(function(idx, drug){
				$printInject.eq(idx).find('span.this-page').text(idx+1);
				if (idx+1 < $printInject.length) {
					$printInject.eq(idx).find('p.pill-list-hint i').text('（以下空白，详见下页）');
				}
			})
		} else {
			console.log('无注射单');
//			$('#printDiv .inject-order').hide();
		}
		*/
	}

	//生成药物单
	function printDrugOrder($printArea, drugOrder, maxRow, idx) {

		if (drugOrder.length == 0) return false;
		var nextOrders = [];
		var groupNo = '';
		var drugUse = '';
		var drippingSpeed = '';
		var frequency = '';
		var prescribingNumber = '';
		var comment = '';
		var onceDose = '';
		var groupCnt = 0;
		var firstRowGroup = '';
		var firstRow = '';
		var e = '';
		var printRow = 0;//打印多少行
		drugOrder.forEach(function(order){
			//药物单
			if (groupNo == '' || order.groupNo == groupNo) {
				groupCnt++;
				if (groupCnt == 1) {
					//分组药物
					firstRowGroup += '<li class="pill-list-item li-w5">';

					firstRowGroup += '<span>'+idx+'、</span>';
					firstRowGroup += '</li>';
					firstRowGroup += '<li class="pill-list-item li-w50">';
					if (order.skinTest.length) {

						firstRowGroup += '<span style="max-width: 180px;display: inline-block;overflow: hidden;white-space: nowrap;">'+order.itemName+'</span>　';
					} else {
						firstRowGroup += '<span style="display: inline-block;overflow: hidden;white-space: nowrap;">'+order.itemName+'</span>　';
					}

					firstRowGroup += '<span style="top: -8px;position: relative;"><b>'+(order.skinTest==1?'[皮试]':'')+'</b></span>';
					firstRowGroup += '</li>';

					firstRowGroup += '<li class="pill-list-item li-w15 text-right">';
					firstRowGroup += '<span>'+(order.spec==null ? '':order.spec)+'</span>';
					firstRowGroup += '</li>';

					firstRowGroup += '<li class="pill-list-item li-w10 text-right" style="border-right: 1px solid;margin-bottom: 0;height:28px;">';
					firstRowGroup += '<span>'+(order.onceDose == null ?'':order.onceDose+order.doseUnit)+'</span>';
					firstRowGroup += '</li>';
					firstRowGroup += '<li class="pill-list-item li-w8">';
					firstRowGroup += '<span name="prescribingNumber"></span>';
					firstRowGroup += '</li>';
					firstRowGroup += '<li class="pill-list-item li-w12 text-right">';
					firstRowGroup += '<span>共'+(order.dosage == null ?'':order.dosage+order.dosageUnit)+'</span>';
					firstRowGroup += '</li>';

					//不分组药物
					firstRow += '<li class="pill-list-item li-w5">';
					firstRow += '<span>'+idx+'、</span>';
					firstRow += '</li>';
					firstRow += '<li class="pill-list-item li-w50">';
					if (order.skinTest.length) {
						firstRow += '<span style="max-width: 180px;display: inline-block;overflow: hidden;white-space: nowrap;">'+order.itemName+'</span>　';
					} else {
						firstRow += '<span style="display: inline-block;overflow: hidden;white-space: nowrap;">'+order.itemName+'</span>　';
					}
					firstRow += '<span style="top: -8px;position: relative;"><b>'+(order.skinTest==1?'[皮试]':'')+'</b></span>';
					firstRow += '</li>';
					firstRow += '<li class="pill-list-item li-w15 text-right">';
					firstRow += '<span>'+(order.spec==null ? '':order.spec)+'</span>';
					firstRow += '</li>';
					firstRow += '<li class="pill-list-item li-w30 text-right">';
					firstRow += '<span>共'+(order.dosage == null ?'':order.dosage+order.dosageUnit)+'</span>';
					firstRow += '</li>';

					comment = (order.comment == null? '':order.comment);
				} else {
					if (groupCnt == 2) {
						e += firstRowGroup;
						printRow++;
					}
					e += '<li class="pill-list-item li-w5">';
					e += '<span> </span>';
					e += '</li>';
					e += '<li class="pill-list-item li-w50">';
//					e += '<span style="max-width: 220px;display: inline-block;overflow: hidden;white-space: nowrap;">'+order.itemName+'</span>　';
					if (order.skinTest.length) {
						e += '<span style="max-width: 180px;display: inline-block;overflow: hidden;white-space: nowrap;">'+order.itemName+'</span>　';
					} else {
						e += '<span style="display: inline-block;overflow: hidden;white-space: nowrap;">'+order.itemName+'</span>　';
					}// modify by zhengxb 2019.03.02

					e += '<span style="top: -8px;position: relative;"><b>'+(order.skinTest==1?'[皮试]':'')+'</b></span>';
					e += '</li>';

					e += '<li class="pill-list-item li-w15 text-right">';
					e += '<span>'+(order.spec==null ? '':order.spec)+'</span>';
					e += '</li>';

					e += '<li class="pill-list-item li-w10 text-right" style="border-right: 1px solid;margin-bottom: 0;height:28px;">';
					e += '<span>'+(order.onceDose == null ?'':order.onceDose+order.doseUnit)+'</span>';
					e += '</li>';
					e += '<li class="pill-list-item li-w8">';
					e += '<span name="prescribingNumber"></span>';
					e += '</li>';
					e += '<li class="pill-list-item li-w12 text-right">';
					e += '<span>共'+(order.dosage == null ?'':order.dosage+order.dosageUnit)+'</span>';
					e += '</li>';
					printRow++;
				}

				groupNo = order.groupNo;
				drippingSpeed = order.drippingSpeed;//滴速
				drugUse = order.drugUseText;
				frequency = order.frequencyText;
				prescribingNumber = order.prescribingNumber;
				onceDose = order.onceDose+order.doseUnit;

			} else {
				nextOrders.push(order);
			}
		});

		//不分组时打印
		if (groupCnt == 1) {
			e += firstRow;
			printRow++;
			e += '<li class="pill-list-item li-w10">';
			e += '</li>';
			e += '<li class="pill-list-item li-w90">';
			e += '<span>用法：'+drugUse+'</span>　';
			e += '<span>每次'+onceDose+'　'+frequency+'</span>　';
			if (drippingSpeed == null || drippingSpeed == '') {
				e += '<span> </span>';
			} else {
				e += '<span>'+drippingSpeed+'滴/分</span>';
			}
			e += '</li>';
			printRow++;

			if (comment!=null) {
				e += '<li class="pill-list-item li-w10">';
				e += '</li>';
				e += '<li class="pill-list-item li-w90">';
				e += '<span>备注：'+comment+'</span>';
				e += '</li>';
				printRow++;
			}
		} else {
			e += '<li class="pill-list-item li-w10">';
			e += '</li>';
			e += '<li class="pill-list-item li-w90">';
			e += '<span>用法：'+drugUse+'</span>　';
			e += '<span>'+frequency+'</span>　';
			if (drippingSpeed == null || drippingSpeed == '') {
				e += '<span> </span>';
			} else {
				e += '<span>'+drippingSpeed+'滴/分</span>';
			}
			e += '</li>';
			printRow++;

			if (comment != null && comment != '') {
				e += '<li class="pill-list-item li-w10">';
				e += '</li>';
				e += '<li class="pill-list-item li-w90">';
				e += '<span>备注：'+comment+'</span>';
				e += '</li>';
				printRow++;
			}
		}

		//一页是否能打下
		if (printRow > maxRow) {
			var $copyPoint = $printArea.clone();
			if (!$printArea.hasClass('copy-print')) {
				$copyPoint.addClass('copy-print');
			}
			$printArea.after($copyPoint);
			var $setUl = $copyPoint.find('div.pill-list-content ul');
			$setUl.empty();

			var $addLine = $(e).appendTo($setUl);
			$addLine.find('span[name="prescribingNumber"]').last().text('X'+prescribingNumber);

			if (nextOrders.length > 0) {
				return printDrugOrder($copyPoint, nextOrders, maxDrugRow-printRow, ++idx);
			} else {
				return idx;
			}
		} else {
			var $setUl = $printArea.find('div.pill-list-content ul');
			var $addLine = $(e).appendTo($setUl);
			$addLine.find('span[name="prescribingNumber"]').last().text('X'+prescribingNumber);

			if (nextOrders.length > 0) {
				return printDrugOrder($printArea, nextOrders, maxRow-printRow, ++idx);
			} else {
				return idx;
			}
		}
	}

	//处方头部
	function userInfo(outpatient) {

		var user = outpatient.user;
		var headPrintInfo = outpatient.printInfo;
		var medical = outpatient.medical;

		var detailInfo = $('div.pill-detailInfo');
		detailInfo.find('span.patient-name').text(medical.name);
		detailInfo.find('span.patient-name').attr('title',medical.name);
		detailInfo.find('span.patient-gender').text(medical.gender==null?'-':medical.gender==1?'男':'女');
		detailInfo.find('span.patient-age').text(medical.showAge);
		$('h2.clinic-name').text($('#institution').val());//诊所名

		console.log(user.fimalyAddr);
		var adph = '';

		if (user.fimalyAddrAllTxt != null && user.fimalyAddrAllTxt.length > 0) {
			adph = user.fimalyAddrAllTxt+'/';
		} else {
			adph = '-/';
		}
		if (user.phone != null && user.phone.length > 0) {
			adph += user.phone;
		} else {
			adph += '-';
		}
		detailInfo.find('span.living-address-countryside').text(adph);
		detailInfo.find('span.diagnosis').text(headPrintInfo.diagnosis);
		detailInfo.find('span.allergies').text(headPrintInfo.allergies);
	}

	function calAmout( prescriptions ) {
		//当前处方
		var totalPrice = 0; // 合计金额
		$(prescriptions).each(function(idx, _prescription) {
			if (_prescription.totalPrice != null && _prescription.totalPrice.length > 0) {
				totalPrice +=  parseInt( _prescription.totalPrice.toString().movePoint(2) , 10);
			}
		});
		return totalPrice.toString().movePoint(-2);
	}

	return {
		resetPrintBody: resetPrintBody,
		printDrugOrder:printDrugOrder,
		userInfo:userInfo
	}
})();